using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace LynxWebLog.Areas.Blogs.Controllers
{
    public class MediaController : Controller
    {
        private string _blogOwner;
        protected override void Initialize(RequestContext requestContext)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            base.Initialize(requestContext);
            this._blogOwner = this.ControllerContext.RouteData.Values["username"].ToString();
        }
        //
        // GET: /Media/
        public async Task<FileContentResult> Get(Int32 id)
        {
            HttpClient client = ClientUtility.BlogAPIClient();
            HttpResponseMessage resp = await client.GetAsync("api/Media/" + id);
            resp.EnsureSuccessStatusCode();

            return await resp.Content.ReadAsAsync<FileContentResult>();
        }

        public async Task<FileContentResult> GetImage(string imgName)
        {
            HttpClient client = ClientUtility.BlogAPIClient();
            HttpResponseMessage resp = await client.GetAsync("api/MediaObjectData/?$filter=username eq '" + _blogOwner + "' and name eq '" + imgName + "'");
            resp.EnsureSuccessStatusCode();

            MediaObjectData mod = (await resp.Content.ReadAsAsync<IEnumerable<MediaObjectData>>()).FirstOrDefault();
            return mod != null ? new FileContentResult(mod.bits, mod.type) : null;

        }
	}
}